package com.uw.uwrpc.core.meta;

import com.alibaba.fastjson.JSON;
import com.uw.uwrpc.core.constant.UWConstant;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(of = {"appId","namespace","env","name"})
public class ServiceMeta {

    private String appId;
    private String namespace;
    private String env;
    private String name;

    private Map<String, String> parameters = new HashMap<>();

    public String serviceSign() {
        return String.join(UWConstant.SEPARATOR, Arrays.asList(appId, namespace, env, name));
    }

    public static ServiceMeta fromServiceSign(String serviceSign) {
        String[] signItems = serviceSign.split(UWConstant.SEPARATOR);
        return ServiceMeta.builder()
                .appId(signItems[0])
                .namespace(signItems[1])
                .env(signItems[2])
                .name(signItems[3])
                .build();
    }

    public String toMetas() {
        return JSON.toJSONString(this.getParameters());
    }
}
